import _ from 'lodash';
import { clickTracker } from './common';

// 处理参数
const getParams = (el, binding) => {
  const params = {
		terminal: 'PC', // 终端 pc/mobile
		eventId: binding.value.eventId, // 事件ID
		payload: binding.value?.payload || {}, // 事件数据
		secondEventId: binding.value?.secondEventId || '', // 二级事件ID，统计一个或者多个eventId eg:详情页按钮的点击，包含详情页多个按钮
    currentPageName: binding.value?.currentPageName || '', // 当前页面的名称，建议所有操作传此参数
  };

  return params;
};

// 已绑定的事件处理函数集合
const FunCollection = {};

// 生成随机函数属性名
const createFunName = () => {
  return `track_f_${(Math.random() * 1000000 + '').split('.')[0]}`;
};

// 点击处理函数
const clickFun = (el, binding) => {
  const params = getParams(el, binding);

  clickTracker(params);

  el.removeEventListener('click', FunCollection[el.dataset.clickFun]);
};

// 埋点事件逻辑
const track = (el, binding, forceRun = false) => {
  const type = binding.value.type;

  if (type === 'click') {
    const cf = el.dataset.clickFun;

    if (cf && FunCollection[cf]) {
      el.removeEventListener('click', FunCollection[cf]);

      delete FunCollection[cf];
    }

    const fs = createFunName();

    FunCollection[fs] = clickFun.bind(null, el, binding);

    el.dataset.clickFun = fs;

    el.addEventListener('click', FunCollection[fs]);
  }
};

// 自定义指令
export const trackDirective = {
  bind: function (el, binding) {
    track(el, binding)
  },
  update: function (el, binding) {
    track(el, binding)
  },
  unbind: function (el, binding) {
    // 移除未触发的事件
    const type = binding.value.type;

    if (type === 'click') {
      const cf = el.dataset.clickFun;

      if (cf && FunCollection[cf]) {
        el.removeEventListener('click', FunCollection[cf]);

        delete FunCollection[cf];
      }
    }
  },
}